package com.cloud.sso.service;

import com.cloud.sso.common.page.AppPageInfo;
import com.cloud.sso.common.util.CollectionUtil;
import com.cloud.sso.common.util.SnowFlakeUtil;
import com.cloud.sso.dto.AppQueryDto;
import com.cloud.sso.dto.AppSaveDto;
import com.cloud.sso.dto.UserQueryDto;
import com.cloud.sso.entity.Application;
import com.cloud.sso.common.exception.AppException;
import com.cloud.sso.entity.User;
import com.cloud.sso.mapper.ApplicationMapper;
import com.cloud.sso.vo.ApplicationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import sun.security.util.ArrayUtil;

import java.util.*;

@Service
public class ApplicationService {

    @Autowired
    private ApplicationMapper applicationMapper;


    @Autowired
    private PasswordEncoder passwordEncoder;
    /**
     * 分页查询应用
     *
     * @param queryDto
     * @return
     */
    public AppPageInfo queryByPage(AppQueryDto queryDto) {

        //计算分页相关属性
        queryDto.setStartIndex();

        List<Application> appList = applicationMapper.queryByPage(queryDto);
        Integer count = applicationMapper.getCount(queryDto);
        AppPageInfo pageInfo = new AppPageInfo(appList, count, queryDto.getPageNum(), queryDto.getPageSize());

        return pageInfo;
    }

    /**
     * 查询所有应用
     *
     * @return
     */
    public List<Application> all() {
        return applicationMapper.selectByMap(null);
    }


    /**
     * 根据clientId查询应用
     *
     * @param clientId
     * @return
     */
    public Application queryByClientId(String clientId) {
        if (clientId == null) {
            throw new AppException("应用clientId不能为空");
        }
        return applicationMapper.getByClientId(clientId);
    }

    /**
     * 保存应用信息
     *
     * @param appSaveDto
     */
    public void saveApplication(AppSaveDto appSaveDto) {

        Application application = new Application();
        BeanUtils.copyProperties(appSaveDto, application);

        application.setClientSecret(passwordEncoder.encode(application.getClientSecret()));

        List<String> grantTypeArray = appSaveDto.getGrantType();
        StringBuilder grantTypeBuilder = new StringBuilder();
        grantTypeArray.stream().forEach(e -> {
            grantTypeBuilder.append(e).append(",");
        });
        application.setGrantType(grantTypeBuilder.substring(0, grantTypeBuilder.lastIndexOf(",")));

        if (appSaveDto.getId() == null) {

            Map<String, Object> map = new HashMap<>();
            map.put("client_id", appSaveDto.getClientId());

            if (CollectionUtil.isNotNull(applicationMapper.selectByMap(map))) {
                throw new AppException("该应用id已经存在");
            }

            application.setId(new SnowFlakeUtil().nextStringId());
            applicationMapper.insert(application);
        } else {
            applicationMapper.updateById(application);
        }
    }

    public ApplicationVo get(String id) {
        return entityToVo(applicationMapper.selectById(id));
    }

    /**
     * 删除应用信息
     *
     * @param id
     */
    public void deleteApplication(String id) {
        Application application = applicationMapper.selectById(id);
        if (application == null) {
            throw new AppException("应用不存在");
        }
        applicationMapper.deleteById(id);
    }

    public ApplicationVo entityToVo(Application application) {
        ApplicationVo applicationVo = new ApplicationVo();

        BeanUtils.copyProperties(application, applicationVo);

        List<String> grantType = new ArrayList<>();

        if (application.getGrantType().contains(",")) {
            String[] grantTypeArray = application.getGrantType().split(",");
            grantType.addAll(Arrays.asList(grantTypeArray));
        } else {
            grantType.add(application.getGrantType());
        }
        applicationVo.setGrantType(grantType);
        return applicationVo;
    }

}
